from PyQt5.QtWidgets import QWidget,QMessageBox
from PyQt5 import uic,QtGui
import os
__dir__ = os.path.dirname(os.path.abspath(__file__))
__ui_dir__ = os.path.join(__dir__, '../ui/Setting.ui')
__icon_dir__ = os.path.join(__dir__, '../icon')

HK_KEY = 'HK_'
MODIFIER = ['control','alt','shift','super']
class Setting(QWidget):
    control = None

    def __init__(self, control):
        super().__init__()
        self.control = control
        # 初始化ui
        uic.loadUi(__ui_dir__, self)
        # 初始化布局
        self.OffMode.setChecked(self.control.config['OFFLINE_MODE'])
        self.TarLanSelector.setCurrentIndex(self.control.config['TARGET_LANGUAGE'])
        self.TimingBaseText.setText(str(self.control.config['READ_SPAN']))
        # 事件注册
        self.TarLanSelector.currentIndexChanged.connect(self.OnTarget)
        self.OffMode.toggled.connect(self.OnOffLine)
        self.TimingBaseText.editingFinished.connect(self.OnReadSpan)
        # 数据双向绑定
        self.bind(self.aPP_ID_LineEdit, 'BAIDU_OCR_APP_ID')
        self.bind(self.aPI_KEY_LineEdit, 'BAIDU_OCR_API_KEY')
        self.bind(self.sECRET_KEY_LineEdit, 'BAIDU_OCR_SECRET_KEY')
        self.bind(self.T_aPP_ID_LineEdit, 'BAIDU_TRAN_APP_ID')
        self.bind(self.T_sECRET_KEY_LineEdit, 'BAIDU_TRAN_SECRET_KEY')
        self.checkHK(self.HK_Text_0, 0)
        self.checkHK(self.HK_Text_1, 1)
        self.checkHK(self.HK_Text_2, 2)
        self.checkHK(self.HK_Text_3, 3)
        self.checkHK(self.HK_Text_4, 4)
        self.setWindowIcon(QtGui.QIcon(__icon_dir__+'\yhd.jpg'))

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        self.control.showMain()
        return super().closeEvent(a0)

    # 改变目标语言
    def OnTarget(self, e):
        # print(e)
        self.control.chanTargetLan(e)

    # 切换离线模式
    def OnOffLine(self, e):
        # print(e)
        self.control.config['OFFLINE_MODE'] = e
        self.control.initTools()

    # 改变定时间隔
    def OnReadSpan(self):
        t = self.sender().text()
        try:
            fl = float(t)
            self.control.config['READ_SPAN'] = fl
        except ValueError:
            self.sender().setText(str(self.control.config['READ_SPAN']))
            QMessageBox.warning(self, "警告", "请输入浮点类型！")
            print('输入错误！')

    # 数据双向绑定
    def bind(self, widget, key):
        widget.setText(self.control.config[key])
        widget.editingFinished.connect(lambda: self.bindKid(widget, key))

    # 帮助bind函数获取widget显示的值
    def bindKid(self, widget, key):
        self.control.config[key] = widget.text()
        print('数据已保存：'+key)

    def checkHK(self, widget, key):
        k = HK_KEY+str(key)
        widget.setText(self.control.config[k])
        widget.editingFinished.connect(lambda: self.checkHKKid(widget, key))

    # 帮助checkHK函数获取widget显示的值
    def checkHKKid(self, widget, key):
        k = HK_KEY+str(key)
        tmp = widget.text()
        arr = tmp.split('+')
        # 表单验证
        if (tmp == '') or self.isKeyBorad(arr):
            self.control.config[k] = tmp
            self.control.setMainHk(key)
            print('数据已保存：' + k)
        else:
            widget.setText(self.control.config[k])
            QMessageBox.warning(self, "警告", "快捷键类型错误！")

    # 确认快捷键是否合法
    def isKeyBorad(self, arr):
        if arr:
            sum = 0
            for x in arr:
                sum += self.ecdKey(x)
            if sum < 4:
                return False
            if sum > 7:
                return False
        return True

    def ecdKey(self, key: str) -> int:
        if len(key) < 1 :
            return 0
        if len(key) == 1:
            if key.isalpha() | key.isdigit():
                return 4
        if key == 'space':
            return 4
        if key[0] == 'f':
            t = key[1:]
            if t.isdigit():
                if 1 <= int(t) <= 12:
                    return 4
        # 最多三个修饰符
        if key in MODIFIER:
            return 1
        # 其他符号均不识别
        return 8